//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { invoke } from "@tauri-apps/api/core";

export type Signature = {
    format: string;
    blob: number[];
    rest: number[];
};

export type PreAuthRequest = {
    user_name: string;
};

export type PreAuthResponse = {
    code: number;
    err_msg: string;
    admin_session_id: string;
    to_sign_str: string;
};


export type AuthRequest = {
    admin_session_id: string;
    sign: Signature;
};

export type AuthResponse = {
    code: number;
    err_msg: string;
};


export async function pre_auth(request: PreAuthRequest): Promise<PreAuthResponse> {
    const cmd = 'admin_auth_api_pre_auth';
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    return invoke<PreAuthResponse>(cmd, {
        request,
    });
}

export async function auth(request: AuthRequest): Promise<AuthResponse> {
    const cmd = 'admin_auth_api_auth';
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    const ret = await invoke<AuthResponse>(cmd, {
        request,
    });
    return ret;
}

//获取当前管理会话ID
export async function get_admin_session(): Promise<string> {
    const cmd = 'admin_auth_api_get_admin_session';
    return invoke<string>(cmd, {});
}

//用私钥对内容签名
export async function sign(privateKeyFile: string, toSignStr: string): Promise<Signature> {
    const cmd = 'admin_auth_api_sign';
    const request = {
        privateKeyFile,
        toSignStr,
    };
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    return invoke<Signature>(cmd, request);
}

//退出登录
export async function logout(): Promise<boolean> {
    const cmd = 'admin_auth_api_logout';
    const globalServer = await invoke<boolean>(cmd, {});
    return globalServer ?? false;
}